import "dayjs/locale/zh-cn"

import { ConfigProvider, theme as antdTheme } from "antd"
import enUS from "antd/es/locale/en_US"
import zhCN from "antd/es/locale/zh_CN"
import dayjs from "dayjs"
import { Suspense, useEffect, useState } from "react"
import { IntlProvider } from "react-intl"
import { useDispatch, useSelector } from "react-redux"

import { localeConfig } from "@/locales"
import { history, HistoryRouter } from "@/routes/history"

import SpinLoad from "./components/common/spinLoad"
import RenderRouter from "./routes"
import { AppState } from "./stores"
import { globalStateType, setGlobalState } from "./stores/global/global.store"
import { getPermissionsAsync, updateNotices } from "./stores/user/user.action"
import { GlobalStyle } from "./styles/globalStyle"
import { configGlobalComponent } from "./utils"
// import LoginPage from "@/pages/login"

const App: React.FC = () => {
	const { theme, locale } = useSelector((state: { global: globalStateType }) => state.global)
	const dispatch = useDispatch()
	const { menuData } = useSelector((state: AppState) => state.user)
	const [antDLocale, setAntDLocale] = useState(zhCN)

	/** initial theme */
	useEffect(() => {
		dispatch(setGlobalState({ theme }))
	}, [theme])
	/** initial locale */
	useEffect(() => {
		switch (locale) {
			case "en_US":
				dayjs.locale("en")
				setAntDLocale(enUS)
				break
			default:
				dayjs.locale("zh-cn")
				setAntDLocale(zhCN)
		}
	}, [locale])
	const intervalReq = () => {
		dispatch(updateNotices())
		setInterval(() => dispatch(updateNotices()), 60000)
	}
	/** initial permissions */
	useEffect(() => {
		const token = localStorage.getItem("t")
		if (token) dispatch(getPermissionsAsync())
		intervalReq()
	}, [])

	return (
		<ConfigProvider
			locale={antDLocale}
			componentSize="middle"
			theme={{
				token: { colorPrimary: "#13c2c2" },
				hashed: false,
				algorithm: theme === "dark" ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm,
				components: configGlobalComponent
			}}
		>
			<IntlProvider locale={locale.split("_")[0]} messages={localeConfig[locale] as Record<string, string>}>
				<HistoryRouter history={history}>
					<Suspense fallback={null}>
						<SpinLoad />
						<RenderRouter menuData={menuData} />
						<GlobalStyle />
					</Suspense>
				</HistoryRouter>
			</IntlProvider>
		</ConfigProvider>
	)
}

export default App
